from motor.motor_asyncio import AsyncIOMotorClient
from pymongo.errors import ConnectionFailure
from typing import Optional
import logging

# Global MongoDB client and database instances
client: Optional[AsyncIOMotorClient] = None
db = None

async def connect_to_mongo(uri: str, db_name: str):
    """Initialize MongoDB connection"""
    global client, db
    try:
        client = AsyncIOMotorClient(uri)
        db = client[db_name]
        # Test the connection
        await client.admin.command('ping')
        logging.info("MongoDB connection established successfully")
    except ConnectionFailure as e:
        logging.error(f"Failed to connect to MongoDB: {e}")
        raise

async def close_mongo_connection():
    """Close MongoDB connection"""
    global client
    if client:
        client.close()
        logging.info("MongoDB connection closed")

def get_database():
    """Get database instance"""
    global db
    return db